package ch08
{
	import flash.display.Sprite;
	import flash.events.Event;

	import utils.Ball;

	/**
	 * 目标偏移
	 * @author sjp
	 *
	 */
	public class OffsetSpring extends Sprite
	{
		private var ball:Ball;
		private var spring:Number=0.1;
		private var vx:Number=0;
		private var vy:Number=0;
		private var friction:Number=0.95;
		//弹簧的长度为 100 像素
		private var springLength:Number=100;
		//重力
		private var gravity:Number=5;

		public function OffsetSpring()
		{
			init();
		}

		private function init():void
		{
			ball=new Ball(20);
			addChild(ball);
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}

		private function onEnterFrame(event:Event):void
		{
			/**
			 * 要寻找目标点，首先要找到物体与固定点之间的夹角，然后沿这个角度从固定点向外展开一段长度——弹簧的长度。
			 * 换句话讲，如果弹簧长度是 50，小球与固定点的夹角是 45 度的话，那么就要以 45 度的夹角向外运动 50 个像素，
			 * 而这个点就是小球的目标点。
			 *
			 * 寻找目标点的代码如下：
			 * var dx:Number = ball.x - fixedX;
			 * var dy:Number = ball.y - fixedY;
			 * var angle:Number = Math.atan2(dy, dx);
			 * var targetX:Number = fixedX + Math.cos(angle) * springLength;
			 * var targetY:Number = fixedY + Math.sin(angle) * springLength;
			 */
			var dx:Number=ball.x - mouseX;
			var dy:Number=ball.y - mouseY;
			var angle:Number=Math.atan2(dy, dx);
			var targetX:Number=mouseX + Math.cos(angle) * springLength;
			var targetY:Number=mouseY + Math.sin(angle) * springLength;
			vx+=(targetX - ball.x) * spring;
			vy+=(targetY - ball.y) * spring + gravity;
			vx*=friction;
			vy*=friction;
			ball.x+=vx;
			ball.y+=vy;
			
			graphics.clear();
			graphics.lineStyle(1);
			graphics.moveTo(ball.x, ball.y);
			graphics.lineTo(mouseX, mouseY);
		}
	}
}